import ObsClient from 'esdk-obs-browserjs'

const ENDPOINT = 'obs.cn-southwest-2.myhuaweicloud.com'

const DEFAULT_TARGET = 'test'

/**
 * 获取ObsClient实例
 * @returns {ObsClient} obsClient
 * @author wangyuan
 */
const getObsClient = () => {
  const ak = '4FGPVUPLKOHPYZIPTSBD'
  const sk = 'm3EJB930RdGWq4lRFimnGBL1d2RrPS2FeWTWWfjJ'
  return new ObsClient({
    access_key_id: ak,
    secret_access_key: sk,
    server: ENDPOINT,
    timeout: 60 * 5
  })
}

/**
 * 获取桶名
 * @returns {String} bucketName
 * @author wangyuan
 */
const getBucket = () => {
  return 'digital-asset'
}

/**
 * 获取objectKey
 * @param {*} file 文件
 * @param {*} target 目标文件夹
 * @returns {String} objectKey
 * @author wangyuan
 */
const getKey = (file: any, target: string) => {
  const timestamp = new Date().valueOf()
  const suffix = file.name.substring(file.name.lastIndexOf('.'), file.name.length)
  if (target) {
    return `${target}/${timestamp}${suffix}`
  } else {
    return `${timestamp}${suffix}`
  }
}

/**
 * 上传文件
 * @param {*} params element-plus el-upload 事件回调值
 * @param {*} target 目标文件夹
 * @returns {Promise} promise
 * @author wangyuan
 */
const uploadFile = (params: any, target = DEFAULT_TARGET) => {
  return new Promise((resolve, reject) => {
    const bucketName = getBucket()
    const file = params.file
    const returner: any = {}
    console.log('上传文件', file)
    const obsClient = getObsClient()
    const key = getKey(file, target)
    console.log('object key', key)
    obsClient
      .putObject({
        Bucket: bucketName,
        Key: key,
        SourceFile: file,
        ACL: 'public-read'
      })
      .then((res: any) => {
        if (res.CommonMsg.Status < 300) {
          const url = `https://${bucketName}.${ENDPOINT}/${key}`
          console.log('object url', url)
          returner.status = 'success'
          returner.url = url
          returner.name = file.name.substring(0, file.name.lastIndexOf('.'))
          returner.msg = '上传成功'
          returner.uid = params.file.uid
          resolve(returner)
        } else {
          returner.status = 'failure'
          returner.msg = res.CommonMsg.Message
          returner.uid = params.file.uid
          reject(returner)
        }
      })
      .catch((err: any) => {
        returner.status = 'failure'
        returner.msg = err
        returner.uid = params.file.uid
        reject(returner)
      })
  })
}

export { uploadFile }
